package com.czx.listener;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czx.common.constants.RedisKeys;
import com.czx.config.DelayedConfig;
import com.czx.dto.EmaiDto;
import com.czx.entity.User;
import com.czx.service.UserService;
import com.czx.util.EmailUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

import static com.alibaba.fastjson2.schema.JSONSchema.Type.Const;


@Slf4j
@Component
public class EmailQueueListener {
    @Autowired
    private EmailUtils emailUtils;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private UserService userService;
    @RabbitListener(queues = "businessQueue")
    public void customerBus(String json, Message message, Channel channel) {
        Map<String,Object> map= JSON.parseObject(json,Map.class);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            String msg = (String) map.get("msg");
            log.debug("map:"+map);
            EmaiDto emaiDto = JSON.parseObject(map.get("emaiDto").toString(), EmaiDto.class);
            //1、注册的情况
            if(msg.equals("reg")){
                new Thread(() -> emailUtils.sendEmail(emaiDto)).start();
                //设置延时队列，延时2小时
                rabbitTemplate.convertAndSend(DelayedConfig.YOUR_EXCHANGE_NAME,DelayedConfig.YOUR_ROUTING_KEY,
                        JSON.toJSONString(emaiDto),
                        message1 ->{
                            message1.getMessageProperties().setHeader("x-delay", RedisKeys.USER_REGISTER_TIME);
                            return message1;
                        } );
            }
            //2、重置密码的情况
            if(msg.equals("reset")){

                new Thread(() -> emailUtils.sendEmail(emaiDto)).start();
            }

            //开始发送邮件

            log.debug("发送邮件成功,应答ACK");
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("发送邮件失败,应答NACK", e);
            try {
                //  第三个参数是该消息是否压入队列，一般都是true，设置false就会丢弃这个消息
                //如果配有死信队列，就可以设置为false
                channel.basicNack(deliveryTag, false, false);
//                channel.basicReject();
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

    // 死信队列的监听
    //@RabbitListener(queues = "dle-queue")
    public void customerDead( Message message, Channel channel) {
        log.debug("发送信息失败，进入死信队列");
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description 注册，延时队列的监听
     * @Author SKY
     * @Date 2023/6/24 11:44
     * @return void
     **/
    @RabbitListener(queues = DelayedConfig.YOUR_QUEUE_NAME)
    public void registerListener(String json,Message message,Channel channel){
        //如果监听到了，代表用户没有激活
        try {
            EmaiDto emaiDto = JSON.parseObject(json, EmaiDto.class);
            QueryWrapper<User> qr = new QueryWrapper<>();
            qr.eq("email", emaiDto.getToUser());
            //自动删除用户信息
            boolean remove = userService.remove(qr);
            log.debug("用户没有点击注册激活码，已删除该消息");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
